import { makeAutoObservable, action } from "mobx";

class AppleStore {
  appleList = [
    {
      id: 0,
      weight: 233,
      isEaten: false,
    },
    {
      id: 1,
      weight: 235,
      isEaten: true,
    },
    {
      id: 2,
      weight: 256,
      isEaten: false,
    },
  ];
  loading = false;
  id = 2;

  constructor() {
    makeAutoObservable(this, {
      eatApple: action.bound,
      pickApple: action.bound,
    });
  }

  get filterAppleByEat() {
    const isEatedAppleList = this.appleList.filter((item) => item.isEaten);
    return {
      isEatedAppleNum: isEatedAppleList.length,
      isEatedAppleWight: isEatedAppleList.reduce(
        (pre, item) => pre + item.weight,
        0
      ),
    };
  }

  get filterNotEatedApple() {
    const notEatedAppleList = this.appleList.filter((item) => !item.isEaten);
    return {
      notEatedAppleList,
      notEatedAppleNum: notEatedAppleList.length,
      notEatedAppleWight: notEatedAppleList.reduce(
        (pre, item) => pre + item.weight,
        0
      ),
    };
  }

  eatApple(id) {
    this.appleList.forEach((item) => {
      if (item.id === id) item.isEaten = true;
    });
  }

  pickApple() {
    if (this.loading) return;
    this.loading = true;
    setTimeout(() => {
      let weight = Math.floor(200 + Math.random() * 50);
      this.id++;
      this.appleList.push({
        id: this.id,
        weight: weight,
        isEaten: false,
      });
      this.loading = false;
    }, 1000);
  }
}

export default AppleStore;
